<template>
	<view class="chat-container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<view class="back-btn" @click="goBack">
				<!-- <text class="iconfont icon-back">←</text> -->
				<text class="iconfont icon-back"></text>
			</view>
			<view class="title">{{ chatInfo.name }}</view>
			<view class="right-btn"></view>
		</view>
		
		<!-- 聊天消息列表 -->
		<scroll-view 
			class="message-list" 
			scroll-y 
			:scroll-top="scrollTop"
			:scroll-with-animation="true"
			@scrolltoupper="loadMoreMessages"
			:enhanced="true"
			:bounces="true"
			:show-scrollbar="false"
			@touchmove.stop.prevent="() => {}"
		>
			<view class="message-wrapper">
				<!-- 加载更多 -->
				<view class="load-more" v-if="hasMore">
					<text>加载更多...</text>
				</view>
				
				<!-- 消息列表 -->
				<view 
					class="message-item"
					v-for="(item, index) in messageList"
					:key="index"
				>
					<!-- 时间戳 -->
					<view class="time-stamp" v-if="showTimestamp(index)">
						<text>{{ formatTime(item.time) }}</text>
					</view>
					
					<!-- 消息内容 -->
					<view class="message-content" :class="{ 'self': item.isSelf }">
						<image 
							class="avatar" 
							:src="item.isSelf ? userAvatar : chatInfo.avatar" 
							mode="aspectFill"
						></image>
						<view class="bubble" :class="{ 'self': item.isSelf }">
							{{ item.content }}
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<!-- 底部输入框 -->
		<view class="input-section">
			<view class="input-box">
				<textarea 
					class="input"
					v-model="inputContent"
					:adjust-position="false"
					:show-confirm-bar="false"
					:cursor-spacing="20"
					:maxlength="500"
					auto-height
					placeholder="请输入消息..."
					@focus="onInputFocus"
					@blur="onInputBlur"
				></textarea>
				<view 
					class="send-btn" 
					:class="{ 'active': inputContent.trim() }"
					@click="sendMessage"
				>发送</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			chatInfo: {
				id: '',
				name: '',
				avatar: '/static/images/service1.png'
			},
			userAvatar: '/static/images/default-avatar.png',
			messageList: [
				{
					content: '您好，请问有什么可以帮您？',
					time: Date.now() - 3600000,
					isSelf: false
				},
				{
					content: '我想咨询一下会员服务',
					time: Date.now() - 3500000,
					isSelf: true
				},
				{
					content: '好的，我们目前有多种会员套餐，您想了解哪个方面呢？',
					time: Date.now() - 3400000,
					isSelf: false
				}
			],
			inputContent: '',
			scrollTop: 0,
			hasMore: true,
			isLoading: false
		}
	},
	onLoad(options) {
		// 获取路由参数
		if (options.id && options.name) {
			this.chatInfo.id = options.id
			this.chatInfo.name = options.name
			this.chatInfo.avatar = `/static/images/service${options.id}.png`
		}
		
		// 加载历史消息
		this.loadHistoryMessages()
	},
	mounted() {
		this.scrollToBottom()
	},
	methods: {
		goBack() {
			uni.navigateBack()
		},
		showTimestamp(index) {
			if (index === 0) return true
			const currentMsg = this.messageList[index]
			const prevMsg = this.messageList[index - 1]
			return currentMsg.time - prevMsg.time > 300000 // 5分钟显示一次时间戳
		},
		formatTime(timestamp) {
			const date = new Date(timestamp)
			const today = new Date()
			const isToday = date.toDateString() === today.toDateString()
			
			if (isToday) {
				return date.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
			}
			return date.toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
		},
		sendMessage() {
			if (!this.inputContent.trim()) return
			
			// 添加新消息
			const newMessage = {
				content: this.inputContent,
				time: Date.now(),
				isSelf: true
			}
			this.messageList.push(newMessage)
			this.inputContent = ''
			this.scrollToBottom()
			
			// 模拟客服回复
			setTimeout(() => {
				const reply = {
					content: '好的，我明白了。请问还有其他问题吗？',
					time: Date.now(),
					isSelf: false
				}
				this.messageList.push(reply)
				this.scrollToBottom()
			}, 1000)
		},
		scrollToBottom() {
			setTimeout(() => {
				const query = uni.createSelectorQuery().in(this)
				query.select('.message-list').boundingClientRect()
				query.exec(res => {
					if (res[0]) {
						this.scrollTop = res[0].height * 2
					}
				})
			}, 100)
		},
		loadMoreMessages() {
			if (this.isLoading || !this.hasMore) return
			
			this.isLoading = true
			// 模拟加载更多消息
			setTimeout(() => {
				const moreMessages = [
					{
						content: '这是更早的消息',
						time: Date.now() - 7200000,
						isSelf: false
					}
				]
				this.messageList.unshift(...moreMessages)
				this.isLoading = false
				
				// 模拟没有更多数据
				if (this.messageList.length > 20) {
					this.hasMore = false
				}
			}, 1000)
		},
		loadHistoryMessages() {
			// TODO: 从服务器加载历史消息
		},
		onInputFocus() {
			this.scrollToBottom()
		},
		onInputBlur() {
			// 可以在这里处理输入框失焦事件
		}
	}
}
</script>

<style lang="scss">
.chat-container {
	height: 100vh;
	background: #f8f9fa;
	display: flex;
	flex-direction: column;
	
	.nav-bar {
		height: 88rpx;
		background: #fff;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 30rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
		
		.back-btn {
			width: 80rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			
			.iconfont {
				font-size: 40rpx;
				color: #333;
			}
		}
		
		.title {
			font-size: 32rpx;
			font-weight: 500;
			color: #333;
		}
		
		.right-btn {
			width: 80rpx;
		}
	}
	
	.message-list {
		flex: 1;
		padding: 20rpx 30rpx;
		
		.message-wrapper {
			.load-more {
				text-align: center;
				font-size: 24rpx;
				color: #999;
				padding: 20rpx 0;
			}
			
			.time-stamp {
				text-align: center;
				margin: 20rpx 0;
				
				text {
					font-size: 24rpx;
					color: #999;
					background: rgba(0,0,0,0.1);
					padding: 4rpx 12rpx;
					border-radius: 8rpx;
				}
			}
			
			.message-content {
				display: flex;
				align-items: flex-start;
				margin-bottom: 30rpx;
				
				&.self {
					flex-direction: row-reverse;
					
					.bubble {
						margin: 0 20rpx 0 0;
						background: #ff69b4;
						color: #fff;
						
						&::before {
							right: -16rpx;
							left: auto;
							border-left-color: #ff69b4;
							border-right-color: transparent;
						}
					}
				}
				
				.avatar {
					width: 80rpx;
					height: 80rpx;
					border-radius: 50%;
					flex-shrink: 0;
				}
				
				.bubble {
					max-width: 60%;
					padding: 20rpx;
					background: #fff;
					border-radius: 12rpx;
					font-size: 28rpx;
					color: #333;
					margin-left: 20rpx;
					position: relative;
					word-break: break-all;
					box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
					
					&::before {
						content: '';
						position: absolute;
						top: 20rpx;
						left: -16rpx;
						border: 8rpx solid transparent;
						border-right-color: #fff;
					}
				}
			}
		}
	}
	
	.input-section {
		background: #fff;
		border-top: 1rpx solid #f0f0f0;
		padding: 20rpx 30rpx;
		padding-bottom: calc(20rpx + constant(safe-area-inset-bottom));
		padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
		
		.input-box {
			display: flex;
			align-items: flex-end;
			
			.input {
				flex: 1;
				min-height: 80rpx;
				max-height: 160rpx;
				background: #f5f5f5;
				border-radius: 40rpx;
				padding: 20rpx 30rpx;
				font-size: 28rpx;
				line-height: 40rpx;
			}
			
			.send-btn {
				width: 120rpx;
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 28rpx;
				color: #999;
				margin-left: 20rpx;
				
				&.active {
					color: #ff69b4;
					font-weight: 500;
				}
			}
		}
	}
}
</style>
